// SOP签核追踪页面

let sopData = [];
let filteredData = [];

// 加载SOP签核追踪页面
function loadSOPPage(container) {
    container.innerHTML = `
        ${createPageTitle('SOP签核追踪', 'fas fa-file-signature')}
        ${createToolbar([
            '<button class="btn btn-primary" onclick="showAddSOPModal()">',
            '<i class="fas fa-plus mr-2"></i>新增SOP',
            '</button>',
            '<button class="btn btn-secondary" onclick="loadSOPData()">',
            '<i class="fas fa-refresh mr-2"></i>刷新',
            '</button>',
            '<button class="btn btn-accent" onclick="exportSOPData()">',
            '<i class="fas fa-download mr-2"></i>导出',
            '</button>',
            '<button class="btn btn-warning" onclick="checkOverdueSOP()">',
            '<i class="fas fa-exclamation-triangle mr-2"></i>检查延期',
            '</button>'
        ])}
        <div id="sop-list">
            ${createSOPTable()}
        </div>
    `;
    
    // 绑定搜索事件
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(handleSOPSearch, 300));
    }
    
    // 加载数据
    loadSOPData();
}

// 创建SOP签核追踪表格
function createSOPTable() {
    const headers = ['SOP编号', 'SOP名称', '机型', '工单号', '版本', '签核状态', '提交日期', '预计签核日期', '实际签核日期', '签核人', '备注', '延期天数'];
    
    return `
        <div class="table-container">
            <table class="table table-zebra w-full">
                <thead>
                    <tr>
                        ${headers.map(header => `<th>${header}</th>`).join('')}
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${filteredData.map(item => {
                        const overdueDays = calculateOverdueDays(item.expectedApprovalDate, item.actualApprovalDate);
                        const statusClass = getSOPStatusClass(item.approvalStatus, overdueDays);
                        
                        return `
                            <tr class="${overdueDays > 0 ? 'overdue-row' : ''}">
                                <td>${item.sopNumber || '-'}</td>
                                <td>${item.sopName || '-'}</td>
                                <td>${item.model || '-'}</td>
                                <td>${item.workOrder || '-'}</td>
                                <td>${item.version || '-'}</td>
                                <td><span class="badge ${statusClass}">${item.approvalStatus || '待签核'}</span></td>
                                <td>${item.submitDate || '-'}</td>
                                <td>${item.expectedApprovalDate || '-'}</td>
                                <td>${item.actualApprovalDate || '-'}</td>
                                <td>${item.approver || '-'}</td>
                                <td>${item.remark || '-'}</td>
                                <td>${overdueDays > 0 ? `<span class="text-red-500 font-bold">${overdueDays}天</span>` : '-'}</td>
                                <td>
                                    <div class="btn-group">
                                        <button class="btn btn-sm btn-primary" onclick="editSOP('${item.id}')">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-error" onclick="deleteSOP('${item.id}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        `;
                    }).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 获取SOP签核状态样式类
function getSOPStatusClass(status, overdueDays) {
    if (status === '已签核') return 'badge-success';
    if (status === '签核中') return 'badge-info';
    if (status === '退回修改') return 'badge-warning';
    if (status === '待签核') return 'badge-ghost';
    if (overdueDays > 0) return 'badge-error';
    return 'badge-ghost';
}

// 加载SOP数据
async function loadSOPData() {
    try {
        const data = await sopAPI.getAll();
        sopData = data;
        filteredData = data;
        updateSOPTable();
    } catch (error) {
        showError('加载数据失败');
    }
}

// 更新SOP表格
function updateSOPTable() {
    const tableContainer = document.getElementById('sop-list');
    if (tableContainer) {
        tableContainer.innerHTML = createSOPTable();
    }
}

// 处理搜索
function handleSOPSearch() {
    const query = document.getElementById('search-input')?.value?.trim() || '';
    
    if (!query) {
        filteredData = sopData;
    } else {
        filteredData = sopData.filter(item => 
            item.sopNumber?.toLowerCase().includes(query.toLowerCase()) ||
            item.sopName?.toLowerCase().includes(query.toLowerCase()) ||
            item.model?.toLowerCase().includes(query.toLowerCase()) ||
            item.workOrder?.toLowerCase().includes(query.toLowerCase()) ||
            item.approver?.toLowerCase().includes(query.toLowerCase()) ||
            item.remark?.toLowerCase().includes(query.toLowerCase())
        );
    }
    
    updateSOPTable();
}

// 显示新增模态框
function showAddSOPModal() {
    const content = `
        <form id="sop-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('SOP编号', 'sopNumber', 'text', '', { required: true, placeholder: '请输入SOP编号' })}
                ${createFormInput('SOP名称', 'sopName', 'text', '', { required: true, placeholder: '请输入SOP名称' })}
                ${createFormInput('机型', 'model', 'text', '', { required: true, placeholder: '请输入机型' })}
                ${createFormInput('工单号', 'workOrder', 'text', '', { required: true, placeholder: '请输入工单号' })}
                ${createFormInput('版本', 'version', 'text', '', { required: true, placeholder: '请输入版本号' })}
                ${createFormInput('签核状态', 'approvalStatus', 'select', '', { 
                    required: true, 
                    options: [
                        { value: '待签核', text: '待签核' },
                        { value: '签核中', text: '签核中' },
                        { value: '退回修改', text: '退回修改' },
                        { value: '已签核', text: '已签核' }
                    ]
                })}
                ${createFormInput('提交日期', 'submitDate', 'date', '', { required: true })}
                ${createFormInput('预计签核日期', 'expectedApprovalDate', 'date', '', { required: true })}
                ${createFormInput('实际签核日期', 'actualApprovalDate', 'date', '')}
                ${createFormInput('签核人', 'approver', 'text', '', { placeholder: '请输入签核人' })}
            </div>
            ${createFormInput('备注', 'remark', 'textarea', '', { placeholder: '请输入备注信息' })}
        </form>
    `;
    
    showModal('新增SOP签核追踪', content, () => {
        const form = document.getElementById('sop-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            createSOP(data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('sop-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                createSOP(data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 创建SOP签核追踪
async function createSOP(data) {
    try {
        await sopAPI.create(data);
        showSuccess('创建成功');
        loadSOPData();
    } catch (error) {
        showError('创建失败');
    }
}

// 编辑SOP签核追踪
function editSOP(id) {
    const item = sopData.find(s => s.id === id);
    if (!item) {
        showError('记录不存在');
        return;
    }
    
    const content = `
        <form id="sop-edit-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('SOP编号', 'sopNumber', 'text', item.sopNumber, { required: true })}
                ${createFormInput('SOP名称', 'sopName', 'text', item.sopName, { required: true })}
                ${createFormInput('机型', 'model', 'text', item.model, { required: true })}
                ${createFormInput('工单号', 'workOrder', 'text', item.workOrder, { required: true })}
                ${createFormInput('版本', 'version', 'text', item.version, { required: true })}
                ${createFormInput('签核状态', 'approvalStatus', 'select', item.approvalStatus, { 
                    required: true, 
                    options: [
                        { value: '待签核', text: '待签核' },
                        { value: '签核中', text: '签核中' },
                        { value: '退回修改', text: '退回修改' },
                        { value: '已签核', text: '已签核' }
                    ]
                })}
                ${createFormInput('提交日期', 'submitDate', 'date', item.submitDate, { required: true })}
                ${createFormInput('预计签核日期', 'expectedApprovalDate', 'date', item.expectedApprovalDate, { required: true })}
                ${createFormInput('实际签核日期', 'actualApprovalDate', 'date', item.actualApprovalDate || '')}
                ${createFormInput('签核人', 'approver', 'text', item.approver || '')}
            </div>
            ${createFormInput('备注', 'remark', 'textarea', item.remark || '')}
        </form>
    `;
    
    showModal('编辑SOP签核追踪', content, () => {
        const form = document.getElementById('sop-edit-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            updateSOP(id, data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('sop-edit-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                updateSOP(id, data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 更新SOP签核追踪
async function updateSOP(id, data) {
    try {
        await sopAPI.update(id, data);
        showSuccess('更新成功');
        loadSOPData();
    } catch (error) {
        showError('更新失败');
    }
}

// 删除SOP签核追踪
function deleteSOP(id) {
    showConfirmDialog('确定要删除这条记录吗？', async () => {
        try {
            await sopAPI.delete(id);
            showSuccess('删除成功');
            loadSOPData();
        } catch (error) {
            showError('删除失败');
        }
    });
}

// 检查延期SOP
async function checkOverdueSOP() {
    try {
        const overdueItems = await sopAPI.getOverdue();
        
        if (overdueItems.length === 0) {
            showInfo('暂无延期项目');
            return;
        }
        
        // 显示延期提醒
        const content = `
            <div class="space-y-4">
                <p class="text-lg font-semibold text-red-600">发现 ${overdueItems.length} 个延期项目</p>
                <div class="overflow-x-auto">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>SOP编号</th>
                                <th>SOP名称</th>
                                <th>机型</th>
                                <th>工单号</th>
                                <th>预计签核日期</th>
                                <th>延期天数</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${overdueItems.map(item => {
                                const overdueDays = calculateOverdueDays(item.expectedApprovalDate, item.actualApprovalDate);
                                return `
                                    <tr class="text-red-600">
                                        <td>${item.sopNumber}</td>
                                        <td>${item.sopName}</td>
                                        <td>${item.model}</td>
                                        <td>${item.workOrder}</td>
                                        <td>${item.expectedApprovalDate}</td>
                                        <td>${overdueDays}天</td>
                                    </tr>
                                `;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        
        showModal('延期提醒', content, null, '确定');
        
    } catch (error) {
        showError('检查延期失败');
    }
}

// 导出SOP数据
function exportSOPData() {
    if (filteredData.length === 0) {
        showWarning('没有数据可导出');
        return;
    }
    
    const exportData = filteredData.map(item => ({
        'SOP编号': item.sopNumber,
        'SOP名称': item.sopName,
        '机型': item.model,
        '工单号': item.workOrder,
        '版本': item.version,
        '签核状态': item.approvalStatus,
        '提交日期': item.submitDate,
        '预计签核日期': item.expectedApprovalDate,
        '实际签核日期': item.actualApprovalDate || '',
        '签核人': item.approver || '',
        '备注': item.remark || '',
        '延期天数': calculateOverdueDays(item.expectedApprovalDate, item.actualApprovalDate)
    }));
    
    exportToCSV(exportData, `SOP签核追踪_${formatDate(new Date(), 'YYYY-MM-DD')}.csv`);
    showSuccess('导出成功');
}

// 绑定到全局作用域
window.loadSOPPage = loadSOPPage;
window.showAddSOPModal = showAddSOPModal;
window.editSOP = editSOP;
window.deleteSOP = deleteSOP;
window.checkOverdueSOP = checkOverdueSOP;
window.exportSOPData = exportSOPData;
